import numpy as np
import csv
import random
from datetime import datetime
from time import strftime

'''
Global and Local Empirical Bayes Smoothers with Gamma Model
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    ra = csv.DictReader(file(fn), dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = float(record[item])
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey

def contiguity_item(ID, contiguigy):
    i = 0
    ROW = contiguigy.shape[0]
    #print ROW
    contiguityItem = []
    j = 0
    
    while i < ROW:
        if contiguigy[i,0]== ID:
            contiguityItem.append(contiguigy[i,1])
            j = j + 1
        i = i + 1
    if j == 1:
        print ID, "does not have contiguity items."
    #elif j == 
    return contiguityItem

def contiguityHashmapItem(ID, contiguigy):
    temp = contiguigy[ID]
    temp = temp.split(',')
    contiguityItem = []
    #print temp
    for item in temp:
        contiguityItem.append(int(item))
    return contiguityItem

def nearestItemWithPopConstraint(ID, contiguigy, denominator, popConstraint, centroids):
    tempSum = denominator[ID];
    conItemList = [ID]
    searchSet = set()
    curID = ID
    curCentroid = centroids[ID,:]    

    while(tempSum < popConstraint):
        tempMinDist = 100000000000
        tempConitguityItem = contiguityHashmapItem(curID, contiguigy)
        for i in tempConitguityItem:
            if((i not in conItemList)):
                searchSet.add(i)

        for i in searchSet:
            tempDist = ((centroids[i,0] - curCentroid[0])**2 + (centroids[i,1] - curCentroid[1])**2)**0.5

            if tempDist < tempMinDist:
                tempMinDist = tempDist
                tempMinID = i
                tempMinpop = denominator[i]

        tempSum = tempSum + tempMinpop
        conItemList.append(tempMinID)
        #print searchSet, tempMinID
        searchSet.remove(tempMinID)
        curID = tempMinID

    return conItemList
#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print "begin at " + getCurTime()
    unitCSV = 'C:/_DATA/migration89_08/COUNTY Migration/SaTScan/exclude_nearest/county.csv'
    contiguityCSV = 'C:/_DATA/migration89_08/COUNTY Migration/SaTScan/exclude_nearest/election2004_Rook.ctg'
    #centroidsCSV = 'C:/_DATA/migration89_08/COUNTY Migration/SaTScan/exclude_nearest/centroids.csv'
    dataMatrix = build_data_list(unitCSV)
    spContiguity = build_data_list(contiguityCSV)
    #centroids = build_data_list(centroidsCSV)
    contiguityHashmap = {}
    excludeIDList = [271, 1259, 2562, 2874, 3080, 3106]
    tempID = np.zeros(max(dataMatrix[:,0])+1)
    for item in tempID:
        item = -1
    i = 0
    for item in dataMatrix[:,0]:
        tempID[int(item)] = i
        i = i + 1
    print dataMatrix
    for item in spContiguity:
        #print int(item[0]), int(item[1])
        if (tempID[int(item[0])] > -1) and (tempID[int(item[1])] > -1):
            temp = ''
            if int(item[0]) in contiguityHashmap:
                temp = contiguityHashmap[int(item[0])] + ','
            contiguityHashmap[int(item[0])] = temp + str(int(tempID[int(item[1])]))
    
    #for item in contiguityHashmap:
        #print item, contiguityHashmapItem(item, contiguityHashmap)
    
    #popConstraint = 10754765.95
    popConstraint = sum(dataMatrix[:,6])/20
    print popConstraint
    neighbor = []
    for i in range(len(dataMatrix)):
        #print i
        temp = nearestItemWithPopConstraint(i, contiguityHashmap, dataMatrix[:,6], popConstraint, dataMatrix[:,10:12])
        #print temp
        neighbor.append(temp)

    filePath = 'C:/_DATA/migration89_08/COUNTY Migration/SaTScan/exclude_nearest/5p_neighbor.csv'
    #np.savetxt(filePath, neighbor, delimiter=',')
    print neighbor

    print "end at " + getCurTime()
    print "==========================="

           
